// 使用window.onload确保页面加载完成后执行代码
window.onload = function () {
    // 发送GET请求获取数据
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/student", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var data = JSON.parse(xhr.responseText);
            console.log(data);
            renderTable(data);
        }
    };
    xhr.send();

    // 渲染表格
    function renderTable(data) {
        var tableBody = document.getElementById("data-body");
        for (var i = 0; i < data.length; i++) {
            var row = document.createElement("tr");

            var idCell = document.createElement("td");
            idCell.textContent = data[i].id;
            row.appendChild(idCell);

            var nameCell = document.createElement("td");
            nameCell.textContent = data[i].name;
            row.appendChild(nameCell);

            var addressCell = document.createElement("td");
            addressCell.textContent = data[i].address;
            row.appendChild(addressCell);

            var phoneCell = document.createElement("td");
            phoneCell.textContent = data[i].phone;
            row.appendChild(phoneCell);

            var actionCell = document.createElement("td");
            var editForm = document.createElement("form");
            editForm.method = "post";
            editForm.action = "/update";
            var editButton = document.createElement("button");
            editButton.type = "submit";
            editButton.textContent = "修改";
            editForm.appendChild(editButton);
            actionCell.appendChild(editForm);

            var deleteForm = document.createElement("form");
            deleteForm.method = "get";
            deleteForm.action = "/delete";
            var deleteButton = document.createElement("button");
            deleteButton.type = "submit";
            deleteButton.textContent = "删除";
            deleteForm.appendChild(deleteButton);
            actionCell.appendChild(deleteForm);

            row.appendChild(actionCell);

            tableBody.appendChild(row);
        }
    }
};